import { Module } from 'vuex'
import { ILoginState, ILoginType, ISysUser } from './types'
import { IRootState } from '../types'
import { accountLoginRequest, getUserMenu } from '@/service/login'
import { ILoginAccount } from '@/service/login/types'
import localCache from '@/utils/cache'
import router from '@/router'
import { ResponseCode } from '@/global'
import { mapMenus2Routes } from '@/utils/map-menus'

// Module 的两个类型是必填项，没有默认值，所以必须准备好
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenu: []
    }
  },
  mutations: {
    updateUserAndToken(state, loginType: ILoginType) {
      state.token = loginType.sysUser.username // 由于后台还未实现 token，暂时以用户名称作为 token
      state.userInfo = { ...loginType.sysUser }
    },
    updateToken(state, token: string) {
      state.token = token
    },
    updateSysUser(state, sysUser: ISysUser) {
      state.userInfo = { ...sysUser }
    },
    updateUserMenu(state, userMenu: any) {
      state.userMenu = userMenu

      const keys = Object.keys(userMenu)
      console.log(keys)
      if (keys.length <= 0) {
        console.log('userMenu是空对象即将推出')
        return
      }
      const routes = mapMenus2Routes(userMenu)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  },
  actions: {
    accountLoginAction({ commit }, payload: ILoginAccount) {
      accountLoginRequest(payload)
        .then((res) => {
          if (!res) {
            console.log('登录请求来了失败的结果：', res)
            return
          }

          const loginRes = res
          console.log('登录请求响应来的结果是：', loginRes)
          if (loginRes.code !== ResponseCode.success) return // 请求失败则直接退出

          // 请求来的数据写入本地缓存 - localStorage
          // 缓存 token,userInfo
          localCache.setCache('userInfo', loginRes.data.sysUser)
          localCache.setCache('token', loginRes.data.sysUser.username)
          const loginType = loginRes.data
          console.log('开始缓存token 和 userInfo')
          commit('updateUserAndToken', loginType)
          console.log('缓存token 和 userInfo结束，开始请求用户菜单')

          // 登录成功了才请求用户菜单权限
          // 登录成功后还要发送请求初始化当前用户的权限，用于跳转到主页后初始化导航菜单
          // const userMenuRes: IResponseResult = await getUserMenu()
          getUserMenu()
            .then((res) => {
              if (!res) {
                console.log('请求用户菜单响应了失败的结果：', res)
                return
              }

              console.log('请求用户菜单得到的响应数据是：', res)

              if (res.code !== ResponseCode.success) return
              localCache.setCache('userMenu', res.data)
              commit('updateUserMenu', res.data)

              // 有菜单数据则跳转到主页
              router.push('/main')
            })
            .catch((e) => {
              console.log('请求用户菜单数据出现异常：', e)
            })
        })
        .catch((e) => {
          console.log('执行登录请求时出现异常：', e)
        })
    },
    // 将 localStorage 缓存的登录数据赋值到 vuex 中
    loadLocalLogin({ commit }) {
      const token = localCache.getCache('token') || ''
      const sysUser: ISysUser = localCache.getCache('userInfo') || {}
      const userMenu = localCache.getCache('userMenu') || {}
      commit('updateToken', token)
      commit('updateSysUser', sysUser)
      commit('updateUserMenu', userMenu)
    }
  }
}

export { loginModule }
